package main

import "fmt"

func main() {

	//切片扩展
	//extend()

	//切片添加
	//add()

	//创建切片
	//create()

	//复制切片
	//copySlice()

	//删除切片中的元素
	deleteSlice()

}

func deleteSlice() {
	fmt.Println("func deleteSlice():")

	s := []int{1, 2, 3, 4, 5, 6}
	fmt.Println("s", s, "len(s):", len(s), "cap(s):", cap(s))

	s = append(s[:2], s[3:]...) //删除3这个元素
	fmt.Println("s", s, "len(s):", len(s), "cap(s):", cap(s))

	s = s[1:] //第一个元素删除后cap变小了
	fmt.Println("s", s, "len(s):", len(s), "cap(s):", cap(s))

	s = append(s[1:2], s[2:]...) //用append第一个元素删除后cap也变小了
	fmt.Println("s", s, "len(s):", len(s), "cap(s):", cap(s))

	s = s[:len(s)-1] //删除最后一个元素与删除中间元素一样cap没有变小
	fmt.Println("s", s, "len(s):", len(s), "cap(s):", cap(s))
	fmt.Println("====================================================")
}

func copySlice() {
	fmt.Println("func copySlice():")
	s1 := []int{1, 2, 3, 4, 5}
	fmt.Println("s1:", s1, "len(s1):", len(s1), "cap(s1):", cap(s1))

	s2 := make([]int, 16) //不指定cap就跟len长度一样
	fmt.Println("s2:", s2, "len(s2):", len(s2), "cap(s2):", cap(s2))

	//s2 = s1  //底层数组是同一个，修改s1,s2也会跟着改变
	copy(s2, s1)
	//s1[0] = 100
	fmt.Println("s2:", s2, "len(s2):", len(s2), "cap(s2):", cap(s2))
	fmt.Println("====================================================")
}

func create() {
	fmt.Println("func create():")
	var s []int
	//容量演示
	for i := 0; i <= 10; i++ {
		fmt.Println("s:", s, "len(s):", len(s), "cap(s):", cap(s))
		s = append(s, i*2+1) //cap不够用时会翻倍扩展
	}
	fmt.Println("s:", s, "len(s):", len(s), "cap(s):", cap(s))

	//声明、定义
	s1 := []int{1, 2, 3, 4, 5}
	fmt.Println("s1:", s1, "len(s1):", len(s1), "cap(s1):", cap(s1))

	s2 := make([]int, 16) //不指定cap就跟len长度一样
	fmt.Println("s2:", s2, "len(s2):", len(s2), "cap(s2):", cap(s2))

	s3 := make([]int, 16, 20) //指定cap
	fmt.Println("s3:", s3, "len(s3):", len(s3), "cap(s3):", cap(s3))
	fmt.Println("====================================================")
}
func extend() {
	fmt.Println("func Extend():")
	//切片可以向后扩展，不超过底层数组cap
	arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
	s1 := arr[2:6]
	s2 := s1[3:5]
	//s2 := s1[3:7] //超过了底层数组
	fmt.Println("s1:", s1, " len(s1):", len(s1), " cap(s1):", cap(s1))
	fmt.Println("s2:", s2, " len(s2):", len(s2), " cap(s2):", cap(s2))
	fmt.Println("====================================================")
}

func add() {
	fmt.Println("func Add():")
	//添加元素超过cap时，会重新分配更大的底层数组
	arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
	s1 := arr[2:6]
	s2 := s1[3:5]
	s3 := append(s2, 10) //s3 = [5 6 10]
	s4 := append(s3, 11) //s4 = [5 6 10 11]
	s5 := append(s4, 12) //s5 = [5 6 10 11 12]
	fmt.Println("arr:", arr)
	fmt.Println("s1:", s1, " len(s1):", len(s1), " cap(s1):", cap(s1))
	fmt.Println("s2:", s2, " len(s2):", len(s2), " cap(s2):", cap(s2))
	fmt.Println("s3:", s3, " len(s3):", len(s3), " cap(s3):", cap(s3))
	fmt.Println("s4:", s4, " len(s4):", len(s4), " cap(s4):", cap(s4))
	fmt.Println("s5:", s5, " len(s5):", len(s5), " cap(s5):", cap(s5))
	fmt.Println("====================================================")
}
